package com.sneaker.shower.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * <h1>IPViewer</h1>
 * <pre>
 * @Description
 * </pre>
 *
 * @Author lopo
 * @Date 2018/10/22
 */
public class IPViewer {
    private static Logger logger = LoggerFactory.getLogger(IPViewer.class);
    private static Boolean bFindIP = false;
    private static InetAddress sip = null;

    public static InetAddress getIP() {
        if (bFindIP == true) {
            return sip;
        }
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                // ----------特定情况，可以考虑用ni.getName判断
                // 遍历所有ip
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    InetAddress s = (InetAddress) ips.nextElement();
                    if (s.isSiteLocalAddress() && !s.isLoopbackAddress() // 127.开头的都是lookback地址
                            && s.getHostAddress().indexOf(":") == -1) {
                        bFindIP = true;
                        ip = s;
                        break;
                    }
                }
            }
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        if (ip != null) {
            sip = ip;
        }
        return ip;

    }

    public static String getIPStr() {
        return getIP().getHostAddress();
    }

    public static void main(String[] args) {
        System.out.println(getIPStr());
    }
}
